<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" label-width="68px">
      <el-form-item label="客户名称" prop="khname">
        <el-input
          v-model="queryParams.khname"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="仪器名称" prop="yqmc">
        <el-input
          v-model="queryParams.yqmc"
          placeholder="请输入仪器名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="完工编号" prop="wgbh">
        <el-input
          v-model="queryParams.wgbh"
          placeholder="请输入完工编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="完工日期" prop="wgsj">
        <el-date-picker
          v-model="queryWgSj"
          @change="selectWgTime"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <span v-show="showSearch">
        <el-form-item label="型号规格" prop="xhgg">
        <el-input
          v-model="queryParams.xhgg"
          placeholder="请输入型号规格"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
        <el-form-item label="制造厂" prop="zzc">
        <el-input
          v-model="queryParams.zzc"
          placeholder="请输入制造厂"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
        <el-form-item label="出厂编号" prop="ccbh">
          <el-input
            v-model="queryParams.ccbh"
            placeholder="请输入出厂编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="管理编号" prop="glbh">
          <el-input
            v-model="queryParams.glbh"
            placeholder="请输入管理编号"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="单价" prop="dj">
          <el-input
            v-model="queryParams.dj"
            placeholder="请输入单价"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="小计" prop="xj">
          <el-input
            v-model="queryParams.xj"
            placeholder="请输入小计"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="备注" prop="bz">
          <el-input
            v-model="queryParams.bz"
            placeholder="请输入备注"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
      </span>
      <el-row style="margin-bottom: 10px;">
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button type="primary" icon="el-icon-d-caret" size="mini" @click="showSearch=!showSearch">{{showSearch ? "隐藏" : "展开"}}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['gd:qybjk:add']"
        >导入</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['gd:qybjk:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['gd:qybjk:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['gd:qybjk:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="info"
          plain
          icon="el-icon-s-order"
          size="mini"
          @click="importLog"
          v-hasPermi="['gd:khbjkPlus:export']"
        >查看导入日志</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="qybjkList" style="width: 100%" @selection-change="handleSelectionChange" @sort-change="sortChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" fixed sortable align="center" prop="xh" width="70" />
      <el-table-column label="仪器名称" fixed sortable align="center" width="120" prop="yqmc">
        <template slot-scope="scope">
          <div style="cursor: pointer;">
            <span> {{scope.row.yqmc}}</span> &nbsp;
            <el-link :underline="false" type="success" @click="copyText(scope.row.yqmc)" icon="el-icon-copy-document" style="font-size: 10px"></el-link>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="完工编号" fixed sortable align="center" width="120" prop="wgbh">
        <template slot-scope="scope">
          <div style="cursor: pointer;">
            <span> {{scope.row.wgbh}}</span> &nbsp;
            <el-link :underline="false" type="success" @click="copyText(scope.row.wgbh)" icon="el-icon-copy-document" style="font-size: 10px"></el-link>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="型号规格" sortable align="center" width="200" prop="xhgg" />
<!--      <el-table-column label="制造厂" sortable align="center" width="120" prop="zzc" />-->
      <el-table-column label="出厂编号" sortable align="center" width="120" prop="ccbh" />
<!--      <el-table-column label="管理编号" sortable align="center" width="120" prop="glbh" />-->
      <el-table-column label="数量" sortable align="center" prop="sl" />
      <el-table-column label="单价" sortable align="center" prop="dj">
        <template slot-scope="scope">
          <div style="cursor: pointer;">
            <span> {{scope.row.dj}}</span> &nbsp;
            <el-link :underline="false" type="success" @click="copyText(scope.row.dj)" icon="el-icon-copy-document" style="font-size: 10px"></el-link>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="小计" sortable align="center" prop="xj" />
      <el-table-column label="服务方式" sortable align="center" width="100" prop="fwfs" />
      <el-table-column label="客户名称" sortable align="center" width="100" prop="khname" />
      <el-table-column label="完工日期" sortable align="center" prop="wgsj" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.wgsj, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" sortable align="center" width="200" prop="bz" />
      <el-table-column label="操作" fixed="right" align="center" width="120" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['gd:qybjk:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['gd:qybjk:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改企业报价库对话框 -->
    <el-dialog :title="title" :visible.sync="open" @close="cancel" width="70%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="请上传完工单" prop="fjid">
              <el-upload
                ref="upload"
                class="upload-demo"
                :action="src"
                name="files"
                :on-success="handleSuccess"
                :on-error="handleError"
                :before-remove="handleRemove"
                :headers="uploadHeaders"
                accept=".xlsx, .xls"
                multiple
                :file-list="fjList"
                :on-preview="handlePreview"
              >
                <el-button size="small" type="primary"> <i class="el-icon-upload"></i> 点击上传</el-button>
                <div slot="tip" class="el-upload__tip">只能上传Excel文件</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">导 入</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="导入日志" :visible.sync="showLog" @close="closeLog" width="90%" append-to-body>
        <logList v-if="showLog"></logList>
    </el-dialog>

  </div>
</template>

<script>
import { listQybjk, getQybjk, delQybjk, importQybjdData } from "@/api/gd/qybjk";
import { getToken } from '@/utils/auth'
import { delFj } from '@/api/gd/fj'
import axios from 'axios'
import logList from '@/views/gd/qybjk/logList.vue'

export default {
  name: "Qybjk",
  components: { logList },
  data() {
    return {
      queryWgSj: [],
      // 附件上传 开始
      src: this.uploadSrc + '/gd/fj/file/batchUpload',
      uploadHeaders: { 'Authorization': 'Bearer ' + getToken() }, // 如果需要CSRF保护的话
      fjList: [],
      // 附件上传 结束
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // 企业报价库表格数据
      qybjkList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        xh: undefined,
        yqmc: undefined,
        xhgg: undefined,
        zzc: undefined,
        ccbh: undefined,
        glbh: undefined,
        sl: undefined,
        dj: undefined,
        xj: undefined,
        fwfs: undefined,
        bz: undefined,
        wgbh: undefined,
        khname: undefined,
        wgsj: undefined,
        params: {
          startTime: '',
          endTime: ''
        }
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      showLog: false
    };
  },
  created() {
    this.getList();
  },
  methods: {
    sortChange({ column, prop, order }) {
      switch (prop) {
        case 'wgbh':
          this.queryParams.orderByCode = order === 'ascending' ? 'wgbh,asc' : 'wgbh,desc'
          break
        case 'yqmc':
          this.queryParams.orderByCode = order === 'ascending' ? 'yqmc,asc' : 'yqmc,desc'
          break
        case 'xhgg':
          this.queryParams.orderByCode = order === 'ascending' ? 'xhgg,asc' : 'xhgg,desc'
          break
        case 'zzc':
          this.queryParams.orderByCode = order === 'ascending' ? 'zzc,asc' : 'zzc,desc'
          break
        case 'ccbh':
          this.queryParams.orderByCode = order === 'ascending' ? 'ccbh,asc' : 'ccbh,desc'
          break
        case 'glbh':
          this.queryParams.orderByCode = order === 'ascending' ? 'glbh,asc' : 'glbh,desc'
          break
        case 'sl':
          this.queryParams.orderByCode = order === 'ascending' ? 'sl,asc' : 'sl,desc'
          break
        case 'dj':
          this.queryParams.orderByCode = order === 'ascending' ? 'dj,asc' : 'dj,desc'
          break
        case 'xj':
          this.queryParams.orderByCode = order === 'ascending' ? 'xj,asc' : 'xj,desc'
          break
        case 'fwfs':
          this.queryParams.orderByCode = order === 'ascending' ? 'fwfs,asc' : 'fwfs,desc'
          break
        case 'bz':
          this.queryParams.orderByCode = order === 'ascending' ? 'bz,asc' : 'bz,desc'
          break
        case 'khname':
          this.queryParams.orderByCode = order === 'ascending' ? 'khname,asc' : 'khname,desc'
          break
        case 'wgsj':
          this.queryParams.orderByCode = order === 'ascending' ? 'wgsj,asc' : 'wgsj,desc'
          break
      }
      this.queryParams.pageNum = 1
      this.getList()
    },
    selectWgTime(time) {
      this.queryParams.params.startTime = time[0]
      this.queryParams.params.endTime = time[1]
    },
    closeLog() {
      this.showLog = false
    },
    importLog() {
      this.showLog =  true
    },
    copyText(data) {
      const textarea = document.createElement('textarea');
      textarea.value = data;
      document.body.appendChild(textarea);
      textarea.select();
      try {
        // 尝试执行复制操作
        const success = document.execCommand('copy');
        if (success) {
          this.$message.success("已复制！")
        } else {
          this.$message.error("复制失败！")
        }
      } catch (error) {
        this.$message.error("复制失败！")
      }
      document.body.removeChild(textarea);
    },
    // ======  上传开始  ======
    handleSuccess(response, file, fileList) {
      if (response !== null && response !== undefined) {
        // 获取当前的上传的附件id
        let fileIds = []
        fileList.forEach(item => {
          if (item.response !== undefined) {
            fileIds.push(item.response[0].fj)
          }
        })
        // 更新状态或者通知用户上传成功
        this.$message.success('上传成功');
        // 上传成功以后，将id设置
        this.form.fjid = fileIds.toString()
      }
    },
    // 上传失败回调
    handleError(err, file) {
      // 处理错误并通知用户
      this.$message.error('上传失败：', err);
      this.fjList = []
    },
    // 删除回调
    handleRemove(file, fileList) {
      // 调用删除附件功能，将附件进行删除
      let fjId = []
      let id = file.id || file.response[0].fj
      fjId.push(id)
      delFj(fjId).then(res => {
        if (res.code === 200) {
          this.$message.success("删除成功！")
        }
      })
    },
    // 文件点击回调
    async handlePreview(file) {
      let id = file.id || file.response[0].fj
      const response = await axios.get(this.uploadSrc + `/gd/fj/download/` + id, { responseType: 'blob', headers: this.uploadHeaders });
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url
      link.download = file.name;
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
    },
    // ======  上传结束  ====
    selectDrlx(val) {
      this.form.drlx = val.toString()
    },
    /** 查询企业报价库列表 */
    getList() {
      this.loading = true;
      listQybjk(this.queryParams).then(response => {
        this.qybjkList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.getList()
    },
    // 表单重置
    reset() {
      this.form = {
        id: undefined,
        xh: undefined,
        yqmc: undefined,
        xhgg: undefined,
        zzc: undefined,
        ccbh: undefined,
        glbh: undefined,
        sl: undefined,
        dj: undefined,
        xj: undefined,
        fwfs: undefined,
        bz: undefined,
        wgbh: undefined,
        khname: undefined,
        wgsj: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      // this.resetForm("queryForm");
      this.queryParams = {
          pageNum: 1,
          pageSize: 10,
          xh: undefined,
          yqmc: undefined,
          xhgg: undefined,
          zzc: undefined,
          ccbh: undefined,
          glbh: undefined,
          sl: undefined,
          dj: undefined,
          xj: undefined,
          fwfs: undefined,
          bz: undefined,
          wgbh: undefined,
          khname: undefined,
          wgsj: undefined,
          params: {
          starTime: '',
            endTime: ''
        }
      }
      this.queryWgSj = []
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.fjList = []
      this.open = true;
      this.title = "导入企业报价库";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getQybjk(id).then(response => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改企业报价库";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;
          importQybjdData(this.form.fjid).then(res => {
            console.log("res", res)
            if (res !== null){
              this.$message.success("导入成功！")
              this.buttonLoading = false;
              this.cancel()
            }
          })
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除企业报价库编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delQybjk(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('gd/qybjk/export', {
        ...this.queryParams
      }, `qybjk_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
